//
//  HMStatusPictureView.swift
//  Black22
//
//  Created by Apple on 16/11/23.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SDWebImage
//  重用标记
private let HMStatusPictureViewCellIdentifier = "HMStatusPictureViewCellIdentifier"


//  每项之间的间距
private let itemMargin: CGFloat = 5

//  每项的宽度
private let itemWidth = CGFloat(Int(ScreenWidth - 20 - 2 * itemMargin) / 3)

//  首页配图视图
class HMStatusPictureView: UICollectionView {

    //  配图数据源
    var picUrls: [HMStatusPicInfo]? {
        didSet {
            //  根据数量计算大小
//            let currentSize = calcSizeWithCount(count: picUrls?.count ?? 0)
//            self.snp_updateConstraints { (make) in
//                make.size.equalTo(currentSize)
//            }
            calcSizeWithCount(count: picUrls?.count ?? 0)
            
            //  重新加载数据源
            reloadData()
            
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    private func setupUI() {
        
        //  注册cell
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        
        
        
    }
    
    //  根据图片个数计算配图大小
    private func calcSizeWithCount(count: Int) {
        
        //  判断图片等于1，从缓存中获取图片，返回单张图片的大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        if picUrls?.count == 1 {
            let imageUrl = picUrls!.first!.thumbnail_pic!
            if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl) {
                
                
                var imageSize = image.size
                //  过窄处理
                if imageSize.width < 80 {
                    let scaleWidth: CGFloat = 80
                    var scaleHeight = scaleWidth / image.size.width * image.size.height
                    if scaleHeight > 150 {
                        scaleHeight = 150
                    }
                    
                    imageSize = CGSize(width: scaleWidth, height: scaleHeight)
                    
                }
                
                // 设置是图片大小
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(imageSize)
                })
                //  设置条目大小
                flowLayout.itemSize = imageSize
                //  立即执行约束条件
                self.layoutIfNeeded()
                //return image.size
            }
            return
        }
        
        
        
        
        //  获取行数和列数
        let cols = count > 3 ? 3 : count
        let rows = (count - 1) / 3 + 1
        
        let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        //  图片个数不为1的时候，设置size大小
        // 设置是图片大小
        self.snp_updateConstraints(closure: { (make) in
            make.size.equalTo(CGSize(width: currentWidth, height: currentHeight))
        })
        //  设置条目大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        //  立即执行约束条件
        self.layoutIfNeeded()
        
        //return CGSize(width: currentWidth, height: currentHeight)
        
        
        
        
    }
    
//    //  设置子控件大小
//    override func layoutSubviews() {
//        super.layoutSubviews()
//        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
//        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
//        flowLayout.minimumLineSpacing = itemMargin
//        flowLayout.minimumInteritemSpacing = itemMargin
//    }
    
    

}

// MARK:    --数据源代理
extension HMStatusPictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMStatusPictureViewCellIdentifier, for: indexPath) as! HMStatusPictureViewCell
        
        cell.picInfo = picUrls![indexPath.item]
        return cell
    }
}

//  自定配图cell
class HMStatusPictureViewCell: UICollectionViewCell {
    
    // MARK:    --懒加载图片
    fileprivate lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  按照图片原比例填充
        imageView.contentMode = .scaleAspectFill
        //  多余部分剪切到
        imageView.clipsToBounds = true
        return imageView
    }()
    
    var picInfo: HMStatusPicInfo? {
        didSet {
            if let imageUrl = picInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
                if imageUrl.hasSuffix(".gif") {
                    gifImageView.isHidden = false
                } else {
                    gifImageView.isHidden = true
                }
                
            }
        }
    }
    
    var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
        
    }
    
}


